<template>
  <XcDrawer ref="drawer" :title="$t('page.app.add')" :width="640" @onDrawerSave="onSave">
    <Form ref="appform" :model="app" :label-width="0" :rules="rules">
      <FormItem prop="name">
        <Input v-model="app.name" maxlength="56" show-word-limit :placeholder="$t('page.app.addform.name')"></Input>
      </FormItem>
      <FormItem prop="remark">
        <Input v-model="app.remark" type="textarea" show-word-limit maxlength="256" :autosize="{minRows:5}" :placeholder="$t('form.remark')"></Input>
      </FormItem>
      <FormItem>
        <Checkbox v-model="app.token">{{$t('page.app.addform.token')}}</Checkbox>
      </FormItem>
    </Form>
  </XcDrawer>
</template>

<script>
  import XcDrawer from '@/components/xcdrawer'
  export default {
    name: "comp-appadd",
    components: { XcDrawer },
    data() {
      return {
        app: {
          name: '',
          remark: '',
          token: false,
        },
        rules: {
          name: [{ required: true, max: 56, pattern: /^[a-z][a-zA-Z0-9_-]{1,55}/, message: this.$t('page.app.addform.namerule'), trigger: 'blur' }],
          remark: [{ required: true, max: 64, message: this.$t('form.inputrule', [this.$t('form.remark')]), trigger: 'blur' }],
        }
      }
    },
    methods: {
      show() {
        this.$refs.appform.resetFields()
        this.$refs.drawer.show()
      },
      onSave() {
        this.$refs.appform.validate((valid) => {
          if (valid) {
            this.$md.dispatch('app_add', this.app).then(data => {
              if (data.retCode === 1) {
                this.$Message.success(this.$t('submitok'))
                this.$refs.drawer.close(true)
                this.$emit('onRefresh')
                if (data.data) {
                  this.$Modal.info({
                    title: this.$t('page.app.addtoken.title'),
                    content: this.$t('page.app.addtoken.content', [data.data])
                  })
                }
              } else {
                switch (data.retMsg) {
                  case 'server.already':
                    this.$Message.error(this.$t(data.retMsg, [this.$t('page.app.addform.name')]))
                    break
                  default:
                    this.$Message.error(this.$t(data.retMsg))
                    break
                }
              }
            })
          }
        })
      },
    }
  };
</script>
